"""
File: 08_发送邮件.py
Author: lvah
Date: 2020-01-14 
Connect: 976131979@qq.com
Description: 

"""
# 设置服务器,用户名、口令以及邮箱的后缀
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

smtp_server = "smtp.163.com"
from_username = '华为云技术中心'
mail_user = "huadoukaihaole0611@163.com"
# 是开启smtp的授权吗不是真实的密码。
mail_password = "python3"
# 邮件主题的前缀
mail_prefix = "[运维开发部]-"


def send_email(to_addrs, subject, msg):
    try:
        # 将要发送的文本信息做MIME封装
        msg = MIMEText(msg)
        # 格式化发件人名称
        msg['From'] = formataddr([from_username, mail_user])
        msg['To'] = to_addrs
        msg['Subject'] = mail_prefix + subject

        # 1. 实例化smtp对象
        server = smtplib.SMTP()
        # 2. 连接邮件服务器
        server.connect(smtp_server)
        # 3. 登录
        server.login(mail_user, mail_password)
        # 4. 发送邮件内容
        server.sendmail(mail_user, to_addrs, msg.as_string())
        # 5. 关闭连接
        server.quit()
    except Exception as  e:
        print(str(e))
        return False
    else:
        return True


if __name__ == '__main__':
    result = send_email('liuxing137965306@qq.com','寒假作业', '请与2月2日之前提交')
    if result:
        print("发送成功.....")
    else:
        print("发送失败.....")